<template>
    <div>
        <a-button type='primary' @click='addNew(null)'>新增</a-button>
    </div>
    <div class="m-t-10">
        <BTable name-key='name' :columns='columns' :data='dataRows' row-key='id'>
            <template #icon="{ record }">
                <BNetImg width="50px" :name="record.icon" :src="record.icon" />
            </template>
            <template #$action='{record}'>
                <BTextButton @click='addNew(record)'>新增</BTextButton>
            </template>
        </BTable>   
    </div>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close='close'>
        <BForm ref='formRef' :label-col='{span : 5}' :fields='formFields'></BForm>
    </BDialog>
</template>

<script lang='ts' setup>
    import { ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, listApi, saveApi, uploadApi } from "@/api/project/Category";
    import { recursionFn } from "@/utils";
    import { useI18nStore } from "@/store/i18n";
    
    const i18n = useI18nStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()

    const formFields:FormField[] = [
        {label : 'id', name : 'id', hidden : true},
        {label : '名称', name : 'name', type : 'text', maxlength : 30, required:true},
        {label : '父分类', name : 'parentId', type : 'treeSelect', required : true, attrs : {allowClear : false}, options : () => [{id : 0, name : '顶级分类'}, ...dataRows.value], labelField : 'name', valueField : 'id', childrenField : 'children'},
        {label : '图标', name : 'icon', type : 'upload', uploadApi : uploadApi, uploadCount : 1, defaultValue : []},
        {label : '链接', name : 'link', type : 'text', maxlength : 50},
        {label : '启用', name : 'enable', type : 'switch', defaultValue : true},
    ]

    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : '名称',
        },

        {
            dataIndex : 'icon',
            title : '图标',
        },

        {
            dataIndex : 'link',
            title : '链接',
        },

        {
            dataIndex : 'enable',
            title : '启用',
        },

        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit(row) {
                dialogTitle.value = i18n.t('update')
                formFields.forEach(field => {
                    if(field.name == 'icon') {
                        field.defaultValue = [row[field.name]]
                    }else {
                        field.defaultValue = row[field.name]
                    }
                    
                })



                visible.value = true
            },

            async $delete(row) {
                const res = await deleteApi(row.id)
                if(res.success) {
                    getList()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])

    const dataRows = ref<any[]>([])



    function getList() {
        listApi().then(res => {
            if(res.data.length > 0) {
                dataRows.value = recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
            }
        })
    }

    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()
    }

    function addNew(parent) {
        dialogTitle.value = i18n.t('add')
        formFields.forEach(field => {
            if(field.name == 'parentId') {
                field.defaultValue = parent ? parent.id : 0
            }else if(field.name == 'icon'){
                field.defaultValue = []
            }else if(field.name == 'enable'){
                field.defaultValue = true
            }else {
                delete field.defaultValue
            }
        })
        visible.value = true
        
    }

    async function submit() {
        let {id, parentId, icon, ...params}  = await formRef.value.validate()

        
        if(id) {
            params.id = id
        }

        if(icon && icon.length > 0) {
            params.icon = icon[0].value
        }

        params.parentId = parentId || 0

        
        const res = await saveApi(params)
        if(res.success) {
            getList()
            message.success(i18n.t('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    getList()

</script>